﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MREO.data;
using System.Data.SqlServerCe;

namespace MREO.gui
{
    public partial class fTemplates : Form
    {
        Connection Conn = new Connection();
        SqlCeDataAdapter adapter = new SqlCeDataAdapter();
        SqlCeCommand command = null;

        SqlCeTransaction tx;

        public string tabKey;

        DataTable mnuDt;

        public fTemplates(DataTable pMnuDt)
        {
            mnuDt = pMnuDt;

            InitializeComponent();

        }

        private int createTree()
        {
            int countTemplates = 0;   // Количество имеющихся шаблонов

            string strSearch = string.Empty;

            treeView_templates.Nodes.Clear();

            foreach (DataRow dr in mnuDt.AsEnumerable())
            {
                TreeNode[] node = null;

                switch (dr["doc_type"].ToString())
                {
                    case "0":
                        node = treeView_templates.Nodes.Find("Заявления", false);
                        if (node.Count() == 0)
                        {
                            treeView_templates.Nodes.Add("Заявления").Name = "Заявления";
                            strSearch = "Заявления";
                        }
                        break;

                    case "1":
                        node = treeView_templates.Nodes.Find("Договора", false);
                        if (node.Count() == 0)
                        {
                            treeView_templates.Nodes.Add("Договора").Name = "Договора";
                            strSearch = "Договора";
                        }
                        break;

                    case "2":
                        node = treeView_templates.Nodes.Find("Карточка", false);
                        if (node.Count() == 0)
                        {
                            treeView_templates.Nodes.Add("Карточка").Name = "Карточка";
                            strSearch = "Карточка";
                        }
                        break;
                }

                node = treeView_templates.Nodes.Find(strSearch, false);

                if (node.Count() > 0)
                {
                    node[0].Nodes.Add(dr["doc_name"].ToString()).Tag = new Object[] { dr["id"], dr["doc_type"], dr["doc_name"], dr["template"], dr["groupDoc"] };
                    countTemplates += 1;
                }
            }

            webBrowser_template.DocumentText = string.Empty;

            return countTemplates;
        }

        // Наполняем дерево записями
        private void fTemplates_Shown(object sender, EventArgs e)
        {
            int countTemplates = createTree();

            tSSLabel_countTempl.Text = "шаблонов: " + countTemplates;
        }

        private void treeView_templates_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView_templates.SelectedNode.Tag == null)
            {
                toolStripButton_add.Enabled = true;
                toolStripButton_edit.Enabled = false;
                toolStripButton_del.Enabled = false;
                return;
            }

            toolStripButton_add.Enabled = false;
            toolStripButton_edit.Enabled = true;
            toolStripButton_del.Enabled = true;

            Object[] oObj = (Object[])treeView_templates.SelectedNode.Tag;

            if (oObj[3].ToString().Length > 0)
            {
                webBrowser_template.DocumentText = Encoding.UTF8.GetString((byte[])oObj[3]);
            }
            else
                webBrowser_template.DocumentText = "";
        }

        /// <summary>
        /// Обновляем дерево, в случае изменения шаблона.
        /// Вызывается из формы редактирования шаблона
        /// </summary>
        public void updateTree(DataTable pNewMNU)
        {
            int countTemplates;

            mnuDt = pNewMNU;

            countTemplates = createTree();
            tSSLabel_countTempl.Text = "шаблонов: " + countTemplates;
        }

        private void toolStripButton_edit_Click(object sender, EventArgs e)
        {
            int idTempl;
            Object[] oObj = (Object[])treeView_templates.SelectedNode.Tag;
            idTempl = int.Parse(oObj[0].ToString());

            fTemplates_AddEdit fTempl = new fTemplates_AddEdit(oObj);
            fTempl.mainForm = this.MdiParent as fMain;
            fTempl.templForm = this;
            fTempl.Text = "Редактирование шаблона " + oObj[2].ToString();
            fTempl.ShowDialog();
        }

        private void toolStripButton_add_Click(object sender, EventArgs e)
        {
            fTemplates_AddEdit fTempl = new fTemplates_AddEdit();
            fTempl.mainForm = this.MdiParent as fMain;
            fTempl.templForm = this;
            fTempl.Text = "Создание шаблона";
            fTempl.ShowDialog();
        }

        private void toolStripButton_del_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            int idTempl;

            Object[] oObj = (Object[])treeView_templates.SelectedNode.Tag;

            idTempl = int.Parse(oObj[0].ToString());

            if (MessageBox.Show("Вы уверены, что хотите удалить шаблон \"" + oObj[2].ToString() + "\"", "Удаление шаблона", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    Conn.con.Open();

                    tx = Conn.con.BeginTransaction();

                    command = new SqlCeCommand("DELETE FROM mnuItems WHERE id = @id"
                                                , Conn.con);
                    command.Transaction = tx;
                    command.Parameters.Add("@id", SqlDbType.Int).Value = idTempl;

                    command.ExecuteNonQuery();

                    command.CommandText = "DELETE FROM templateParam WHERE mnuItems = @id";

                    command.ExecuteNonQuery();

                    tx.Commit();

                }
                catch (Exception exc) { tx.Rollback(); throw new Exception(exc.Message); }
                finally
                {
                    command.Dispose();
                    adapter.Dispose();
                    if (Conn.con.State == ConnectionState.Open)
                        Conn.con.Close();
                }
            }

            //перечитываем меню
            supportMethod supMethod = new supportMethod();
            dt = supMethod.loadMnu();

            updateTree(dt);

        }
    }
}
